package com.air.antispider.stream.dataprocess.businessprocess

import com.air.antispider.stream.commom.util.jedis.PropertiesUtil

/**
  * 数据切割，将一整条数据切成多个字段
  */
object DataSplit {
  def dataSplit(message: String): (String, String, String, String, String,
    String, String, String, String, String, String, String) = {
    var request = ""
    var requestMethod = ""
    var contentType = ""
    var requestBody = ""
    var httpReferrer = ""
    var remoteAddr = ""
    var httpUserAgent = ""
    var timeIso8601 = ""
    var serverAddr = ""
    var cookiesStr = ""
    var cookieValue_JSESSIONID = ""
    var cookieValue_USERID = ""

    val messageArr: Array[String] = message.split("#CS#")
    if (messageArr.length > 1) {
      //说明有数据
      val requestMsg: String = messageArr(1)
      //使用空格做切割,拿url数据
      val requestArr: Array[String] = requestMsg.split(" ")
      if (requestArr.length > 1) {
        //取出URL数据 /B2C40/dist/main/modules/common/requireConfig.js
        request = requestArr(1)
      }
    }
    //获取请求方式
    if (messageArr.length > 2) {
      requestMethod = messageArr(2)
    }
    //获取请求类型
    if (messageArr.length > 3) {
      contentType = messageArr(3)
    }
    //获取请求请求体内容
    if (messageArr.length > 4) {
      requestBody = messageArr(4)
    }
    //获取来源的URL
    if (messageArr.length > 5) {
      httpReferrer = messageArr(5)
    }
    //获取请求的客户端IP
    if (messageArr.length > 6) {
      remoteAddr = messageArr(6)
    }
    //获取请求方式
    if (messageArr.length > 7) {
      httpUserAgent = messageArr(7)
    } //获取请求时间
    if (messageArr.length > 8) {
      timeIso8601 = messageArr(8)
    }
    //获取请求的服务器IP
    if (messageArr.length > 9) {
      serverAddr = messageArr(9)
    }
    //获取请求携带的cookie信息
    if (messageArr.length > 10) {
      cookiesStr = messageArr(10)
    }

    //对原始cookie数据使用"; "进行切割,拿到所有的cookie键值对
    val cookieArr: Array[String] = cookiesStr.split("; ")
    for (cookie <- cookieArr) {
      //此时获取到的Cookie : JSESSIONID=782121159357B98CA6112554CF44321E
      //将cookie使用"="进行切割,得到具体的数据
      val cooArr: Array[String] = cookie.split("=")
      if (cooArr.length > 1) {
        //这个cookie有键和值
        val cookieName = cooArr(0)
        val cookieValue = cooArr(1)

        //判断这个Cookie是否是我们需要的
        val jSessionIDCookieName: String = PropertiesUtil.getStringByKey("cookie.JSESSIONID.key", "cookieConfig.properties")
        val userIDCookieName: String = PropertiesUtil.getStringByKey("cookie.userId.key", "cookieConfig.properties")

        if (cookieName.equalsIgnoreCase(jSessionIDCookieName)) {
          cookieValue_JSESSIONID = cookieValue
        }
        if (cookieName.equalsIgnoreCase(userIDCookieName)) {
          cookieValue_USERID = cookieValue
        }
      }
    }

    //    将数据封装为元组返回
    (request, requestMethod, contentType, requestBody, httpReferrer,
      remoteAddr, httpUserAgent, timeIso8601, serverAddr, cookiesStr,
      cookieValue_JSESSIONID, cookieValue_USERID)
  }

}
